package com.sikadwafastdaisfondturbo.pretloan.utils.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Typeface
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.tabs.TabLayout
import com.sikadwafastdaisfondturbo.lib_baseadapter.SikadwaOnItemChildClickListener
import com.sikadwafastdaisfondturbo.lib_baseadapter.SikadwaRecyclerViewAdapter
import com.sikadwafastdaisfondturbo.lib_baseadapter.SikadwaViewHolderHelper
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.app.App
import com.sikadwafastdaisfondturbo.pretloan.databinding.DialogBirthdayBinding
import com.sikadwafastdaisfondturbo.pretloan.databinding.ItemMonthBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.DensityUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.helper.DateHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.http.HttpHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.rv.GridDecoration
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Calendar

/**
 * Author : wwdeng
 * Date : 2024/5/23 15:44
 * <p>
 * 每天进步一点点
 * <p>
 * Desc : 流程选择出生日期
 */
class BirthdayDialog: ProDialog {
    private lateinit var binding: DialogBirthdayBinding
    private var mCallback: IDialogCallback? = null
    //事件备注
    private var eventRemark = ""
    /* 日期 */
    private var mDayAdapter: DayAdapter? = null

    //年
    private var showYear = DateHelper.getEighteenYearsBefore()
    //月
    private var isInit = true
    private var showMonth = DateHelper.getCurtMonth()
    //日
    private var showDay = DateHelper.getCurtDay()

    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    constructor(context: Context?, remark: String,callback: IDialogCallback?) : super(context) {
        mCallback = callback
        eventRemark = remark
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback){
        this.mCallback = callback
    }

    override fun initWindow() {
        val params = window?.attributes
        params?.width = App.getPhoneWidth()
        params?.height = WindowManager.LayoutParams.WRAP_CONTENT
        window?.attributes = params
        window?.setWindowAnimations(R.style.dialog_slide_anim) //修改动画样式
        window?.setGravity(Gravity.BOTTOM)
    }

    override fun getRootView(): View {
        binding = DialogBirthdayBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initView() {
        initMonthTabLayout()
        initRvDay()
    }

    override fun initListener() {
        setOnClickListener(R.id.btnDone)
        //上一年
        binding.imgLastYear.setOnClickListener {
            showYear--
            showYear()
            showDay()
        }
        //下一年
        binding.imgNextYear.setOnClickListener {
            //不能选择
            if (showYear >= DateHelper.getEighteenYearsBefore()){
                return@setOnClickListener
            }
            showYear++
            showYear()
            showDay()
        }
    }

    override fun initData() {
        showYear()
        showMonth()
        showDay()
    }

    @SuppressLint("SimpleDateFormat")
    override fun onViewClick(v: View?) {
        when (v?.id) {
            R.id.btnDone -> {//提交
                val selectDay = getSelectDay()
                if (selectDay == 0){
                    showToast(context.getString(R.string.tips_select_birth_error))
                    return
                }
                dismiss()
                var formatDay = "$selectDay"
                if (selectDay < 10){
                    formatDay = "0$selectDay"
                }

                val calendar = Calendar.getInstance()
                calendar.set(Calendar.YEAR, showYear)
                calendar.set(Calendar.MONTH, showMonth-1)
                calendar.set(Calendar.DAY_OF_MONTH, selectDay)
                val obj = JSONObject()
                obj.put("showDate","$showYear-${DateHelper.getMonthList()[showMonth - 1].optString("month")}-$formatDay")
                obj.put("subDate",SimpleDateFormat("yyyy-MM-dd").format(calendar.timeInMillis))
                if (mCallback != null){
                    mCallback?.completed(obj)
                }
            }
        }
    }

    interface IDialogCallback {
        fun completed(selectDate: JSONObject)
    }

    /**
     * 设置月份
     */
    private fun initMonthTabLayout(){
        binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.setSelected(tab)
            }
            override fun onTabUnselected(tab: TabLayout.Tab?) {
                tab?.setUnselected()
            }
            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initRvDay() {
        binding.rvDay.setHasFixedSize(true)
        binding.rvDay.isNestedScrollingEnabled = false
        binding.rvDay.isFocusableInTouchMode = false //不需要焦点
        val decoration = DensityUtils.dp2px(12f)
        binding.rvDay.addItemDecoration(GridDecoration(7,decoration,true))
        val layoutManager = GridLayoutManager(context,7)
        binding.rvDay.layoutManager = layoutManager
        mDayAdapter = DayAdapter(binding.rvDay)
        binding.rvDay.adapter = mDayAdapter
        binding.rvDay.itemAnimator = DefaultItemAnimator()
        mDayAdapter?.setOnItemChildClickListener(SikadwaOnItemChildClickListener { _, childView, position ->
            mDayAdapter?.let {
                val item = it.getItem(position)
                if (item.optBoolean("isSelect") || item.optInt("day") == 0){
                    return@SikadwaOnItemChildClickListener
                }
                if (item.optInt("year") == DateHelper.getEighteenYearsBefore()
                    && item.optInt("month") == DateHelper.getCurtMonth()
                    && item.optInt("day") > DateHelper.getCurtDay()){
                    return@SikadwaOnItemChildClickListener
                }

                for (i in 0..< it.itemCount){
                    val obj = it.getItem(i)
                    obj.put("isSelect",false)
                    if (i == position){
                        obj.put("isSelect",true)
                    }
                }
            }
            mDayAdapter?.notifyDataSetChanged()
        })
    }

    /**
     * 选中状态
     */
    fun TabLayout.Tab.setSelected(tab: TabLayout.Tab) {
        this.customView?.let {
            val textMonth = it.findViewById<TextView>(R.id.textMonth)
            textMonth.setTypeface(Typeface.DEFAULT,Typeface.BOLD)
            textMonth.setTextColor(ContextCompat.getColor(context,R.color.FF4C8FFB))
            textMonth.setBackgroundResource(R.drawable.radius_fill_ffdff0ff_4)
        }
        if (!isInit){
            showMonth = tab.position + 1
            showDay()
        }
        isInit = false
    }

    /**
     * 未选中状态
     */
    fun TabLayout.Tab.setUnselected() {
        this.customView?.let {
            val textMonth = it.findViewById<TextView>(R.id.textMonth)
            textMonth.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
            textMonth.setTextColor(ContextCompat.getColor(context,R.color.FF666666))
            textMonth.setBackgroundColor(ContextCompat.getColor(context,R.color.transparent))
        }
    }

    /**
     * 设置年份
     */
    private fun showYear(){
        binding.textYear.text = "$showYear"
    }

    /**
     * 设置月份
     */
    private fun showMonth(){
        binding.tabLayout.removeAllTabs()
        val monthList = DateHelper.getMonthList()
        monthList.forEach {
            it.put("year",showYear)
            val tab = binding.tabLayout.newTab()
            val tabBinding = ItemMonthBinding.inflate(LayoutInflater.from(context))
            tabBinding.textMonth.text = it.optString("month")
            tab.setCustomView(tabBinding.root)
            binding.tabLayout.addTab(tab)
        }

        val curtIndex = showMonth - 1
        binding.tabLayout.getTabAt(curtIndex)?.select()
        binding.tabLayout.post {
            binding.tabLayout.setScrollPosition(curtIndex,0f,false)
        }
    }

    /**
     * 设置日期
     */
    private fun showDay(){
        val dayList = arrayListOf<JSONObject>()
        //指定年月的1号是星期几
        val week = DateHelper.getDayOfWeek(showYear,showMonth,1)
        for (i in 0..<week){
            val item  = JSONObject()
            item.put("year",0)
            item.put("month",0)
            item.put("day",0)
            dayList.add(item)
        }
        dayList.addAll(DateHelper.getDayList(showYear,showMonth))
        for (i in 0..<dayList.size){
            val day = dayList[i]
            day.put("isSelect",false)
            if (showYear == DateHelper.getEighteenYearsBefore() && showMonth == DateHelper.getCurtMonth() && day.optInt("day") == showDay){
                day.put("isSelect",true)
            }
        }
        mDayAdapter?.data = dayList
    }

    /**
     * 获取选中的日期
     */
    private fun getSelectDay(): Int{
        var day = 0
        mDayAdapter?.let {
            for (i in 0..< it.itemCount){
                val item = it.getItem(i)
                if (item.optBoolean("isSelect")){
                    day = item.optInt("day")
                    break
                }
            }
        }
        return day
    }

    /**
     * 日期
     */
    internal inner class DayAdapter(recyclerView: RecyclerView?) :
        SikadwaRecyclerViewAdapter<JSONObject>(recyclerView, R.layout.item_day) {
        override fun setItemChildListener(helper: SikadwaViewHolderHelper, viewType: Int) {
            helper.setItemChildClickListener(R.id.textDay) //点击Item
        }

        override fun fillData(helper: SikadwaViewHolderHelper, position: Int, model: JSONObject) {
            val textDay = helper.getTextView(R.id.textDay)
            val showDay = model.optInt("day")
            if (showDay == 0){
                textDay.text = ""
            } else {
                textDay.text = "$showDay"
            }

            if (model.optBoolean("isEnabled")){
                if (model.optBoolean("isSelect")){
                    textDay.setTypeface(Typeface.DEFAULT,Typeface.BOLD)
                    textDay.setTextColor(ContextCompat.getColor(context,R.color.FF4C8FFB))
                    textDay.setBackgroundResource(R.drawable.radius_fill_ffdff0ff_4)
                } else {
                    textDay.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
                    textDay.setTextColor(ContextCompat.getColor(context,R.color.black))
                    textDay.setBackgroundColor(ContextCompat.getColor(context,R.color.transparent))
                }
            } else {
                textDay.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
                textDay.setTextColor(ContextCompat.getColor(context,R.color.FFBFBFBF))
                textDay.setBackgroundColor(ContextCompat.getColor(context,R.color.transparent))
            }
        }
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addEvent(EventType.DIALOG.DIALOG_BIRTHDAY_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        HttpHelper.addEvent(EventType.DIALOG.DIALOG_BIRTHDAY_DISMISS,eventRemark)
    }
}